package com.atguigu.petstore.common.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author lfy
 * @Description
 * @create 2023-09-22 10:00
 */
public class CaptchaUtil {

    public static BufferedImage getCaptchaImg(String code){
        int width = 200;
        int height = 80;

        // 创建一个空白图像
        BufferedImage captchaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取图像的绘图上下文
        Graphics2D g2d = captchaImage.createGraphics();

        // 设置背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);


        // 设置字体和颜色
        g2d.setFont(new Font("Arial", Font.BOLD, 36));
        g2d.setColor(Color.BLACK);

        // 生成随机验证码
        String captchaText = code; // 5位验证码
        g2d.drawString(captchaText, 50, 50);

        // 添加噪点
        addNoise(g2d);

        // 绘制线条
        drawLines(g2d);

        // 释放绘图上下文资源
        g2d.dispose();

        // 保存验证码图像
        // 可以使用 ImageIO.write 方法将图像保存到文件中
        return captchaImage;
    }

    // 生成随机验证码
    public static String generateRandomCaptcha(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            captcha.append(characters.charAt(index));
        }
        return captcha.toString();
    }

    // 添加噪点
    private static void addNoise(Graphics2D g2d) {
        Random random = new Random();
        int noiseLevel = 150; // 噪点数量

        for (int i = 0; i < noiseLevel; i++) {
            int x = random.nextInt(200);
            int y = random.nextInt(80);
            int grayValue = random.nextInt(256); // 随机灰度值
            g2d.setColor(new Color(grayValue, grayValue, grayValue));
            g2d.fillRect(x, y, 1, 1);
        }
    }

    // 绘制线条
    private static void drawLines(Graphics2D g2d) {
        Random random = new Random();
        int numLines = 5; // 线条数量

        for (int i = 0; i < numLines; i++) {
            int x1 = random.nextInt(200);
            int y1 = random.nextInt(80);
            int x2 = random.nextInt(200);
            int y2 = random.nextInt(80);
            g2d.setColor(Color.GRAY);
            g2d.drawLine(x1, y1, x2, y2);
        }
    }
}
